<?php


namespace App\Http\Controllers;


use App\Helpers\Helpers;
use App\Model\Cart;
use App\Model\Setting;
use Illuminate\Database\Eloquent\Collection;

class CartController extends Controller
{
    public function index()
    {
        $userId = Helpers::getUserId();

        // 查询购物车状态
        /** @var Cart[]|Collection $carts */
        $carts = Cart::with('goods')->where('user_id', Helpers::getUserId())->get();

        $total = 0;
        foreach ($carts  as $cart) {
            $total = $total + $cart->number * $cart->goods->goods_price;
        }
        $total = number_format($total, 2);

        return view('home.cart', [
            'count' => $carts->count(),
            'total' => $total,
            'shopping_price' => Setting::getShoppingPrice(),
            'carts' => $carts
        ]);
    }

    public function checkout()
    {
        // 查询购物车状态
        /** @var Cart[]|Collection $carts */
        $carts = Cart::with('goods')->where('user_id', Helpers::getUserId())->get();

        if ($carts->count() <= 0) {
            abort(404);
        }

        $total = 0;
        foreach ($carts  as $cart) {
            $total = $total + $cart->number * $cart->goods->goods_price;
        }
        $total = number_format($total, 2);

        return view('home.checkout', [
            'total' => $total,
            'count' => $carts->count(),
            'carts' => $carts,
            'shopping_price' => Setting::getShoppingPrice(),
            'client_id' => getenv("CLIENT_ID")
        ]);
    }

    public function remove()
    {
        $id = request()->input('id');
        $cart = Cart::find($id);

        $cart->delete();

        return response()->json([
            'status' => 'success'
        ]);
    }

}
